<?php
/**
 * dttvb_chat page.
 *
 * @copyright Copyright (C) 2008 the DtTvB (http://dt.in.th/)
 * @license http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
 * @package dttvb_chat
 */

if (!defined('FORUM_ROOT'))
	define('FORUM_ROOT', '../../');
require FORUM_ROOT . 'include/common.php';

if (!defined('FORUM_PAGE'))
	define('FORUM_PAGE', 'dttvb_chat');

($hook = get_hook('xn_dtchat_start')) ? (defined('FORUM_USE_INCLUDE') ? include $hook : eval($hook)) : null;

// Load various data.
$ext_info = array(
	'id' => 'dttvb_chat'
);
$ext_info['path'] = FORUM_ROOT . 'extensions/' . $ext_info['id'];
$ext_info['url'] = $GLOBALS['base_url'] . '/extensions/' . $ext_info['id'];

if (file_exists($ext_info['path'].'/lang/'.$forum_user['language'].'.php'))
	require $ext_info['path'].'/lang/'.$forum_user['language'].'.php';
else
	require $ext_info['path'].'/lang/English.php';

if ($forum_user['id'] == 1)
	message($lang_chat['Login to chat']);

if (isset($_GET['mode']) && $_GET['mode'] == 'gateway') {

	require FORUM_ROOT.'include/parser.php';
	function dttvb_chat_get_msg($since = 0) {
		global $forum_db;
		$query = array(
			'SELECT'	=> 'c.id, c.poster, c.message, c.posted',
			'FROM'		=> 'dttvbchat AS c',
			'WHERE'     => 'c.id > ' . intval($since),
			'ORDER BY'	=> 'c.id DESC',
			'LIMIT'		=> 20
		);
		$result = $forum_db->query_build($query);
		$o = array();
		while ($row = $forum_db->fetch_assoc($result)) {
			array_unshift ($o, $row);
		}
		return $o;
	}
	function dttvb_chat_get_online() {
		global $forum_db;
		$query = array(
			'SELECT'	=> 'c.user_id, c.username',
			'FROM'		=> 'dttvbchatonline AS c',
			'WHERE'     => 'c.updated > ' . (time() - 30)
		);
		$result = $forum_db->query_build($query);
		$o = array();
		while ($row = $forum_db->fetch_assoc($result)) {
			$o[$row['user_id']] = $row['username'];
		}
		return $o;
	}
	function dttvb_chat_put_msg($txt, $user = null) {
		global $forum_db, $forum_user;
		if ($user === null)
			$user = $forum_user['username'];
		if (trim($txt) == '') {
			return;
		}
		$query = array(
			'INSERT'  => 'poster, message, posted',
			'INTO'    => 'dttvbchat',
			'VALUES'  => array(
				'\'' . $forum_db->escape($user) . '\',' .
				'\'' . $forum_db->escape(forum_htmlencode(forum_trim($txt))) . '\',' .
				time()
			)
		);
		$result = $forum_db->query_build($query);
	}
	function dttvb_chat_error($msg) {
		echo '{"status":"ok","method":"error","result":"' . addslashes($msg) . '"}';
	}
	function dttvb_chat_json($id) {
		$msgs = dttvb_chat_get_msg($id);
		$online = dttvb_chat_get_online();
		echo '{"status":"ok","method":"update","result":{"messages":[';
		$o = array();
		foreach ($msgs as $v) {
			$f = '{' .
				'"id":' . $v['id'] . ',' . 
				'"poster":"' . addslashes($v['poster']) . '",' .
				'"message":"' . addslashes(do_smilies($v['message'])) . '",' .
				'"posted":"' . addslashes(format_time($v['posted'], 2, null, 'H:i:s')) . '",' . 
				'"timediff":' . (time() - $v['posted']) . '}';
			$o[] = $f;
		}
		echo implode(',', $o);
		echo '],"online":{';
		$o = array();
		foreach ($online as $k => $v) {
			$f = '"' . addslashes($k) . '":"' . addslashes($v) . '"';
			$o[] = $f;
		}
		echo implode(',', $o);
		echo '}}}';
	}
	if (isset($_POST['message'])) {
		dttvb_chat_put_msg ($_POST['message']);
	}
	dttvb_chat_json (isset($_POST['since_id']) ? intval($_POST['since_id']) : 0);
	$query = array(
		'REPLACE'  => 'user_id, username, updated',
		'INTO'    => 'dttvbchatonline',
		'VALUES'  => 
			$forum_user['id'] . ',\'' . $forum_db->escape($forum_user['username']) . '\',' .
			time()
	);
	$result = $forum_db->query_build($query);
	$forum_db->close();
	exit;
}




$forum_page['main_head'] = $lang_chat['Chat'];
$forum_page['crumbs'] = array(
	array($forum_config['o_board_title'], forum_link($forum_url['index'])),
	$lang_chat['Chat']
);

// Display header
require FORUM_ROOT.'header.php';
ob_start();
($hook = get_hook('xn_dtchat_main_output_start')) ? (defined('FORUM_USE_INCLUDE') ? include $hook : eval($hook)) : null;


// Show box
?>

<div class="main-content">
	<div id="chat_layer" style="position:relative">
		<div id="chat_new" style="display:none;cursor:pointer;position:absolute;top:10px;left:10px;z-index:2;background:#fff;color:#000;border:1px solid #000;line-height:2em;padding:0 1em;font-weight:bold"><?php echo $lang_chat['Msg alert'] ?></div>
	</div>
	<div id="chat_onlinelist" style="height: 25em; overflow: auto; overflow-x: hidden;width:14.5em;float:right">
		<div style="padding: 1ex;">
			<b><?php echo $lang_chat['Online list']; ?></b>
			<div id="chat_onlines"></div>
		</div>
	</div>
	<div id="chat_data" style="height: 25em; overflow: auto; overflow-x: hidden;margin-right:15em;">
		<div style="padding: 1ex;" id="chat_contents">
		</div>
	</div>
	<form action="<?php echo $ext_info['url']; ?>/noscript.html" id="chatform">
	<fieldset class="frm-group group1">
		<div class="sf-set set1">
			<div class="sf-box text">
				<label for="fld1"><span><?php echo $lang_chat['Write message']; ?>:</span></label><br/>
				<span class="fld-input"><input type="text" size="50" name="message" id="fld1"/>
				<input type="submit" value="<?php echo $lang_chat['Shout']; ?>" /></span>
			</div>
		</div>
	</fieldset>
	</form>
</div>

<div style="text-align: center; color: #888; font-size: 0.9em; margin-top: 1ex;">
	Chat Box Extension by <a href="http://dt.in.th/" style="color: #777;">the DtTvB</a>
</div>
<script type="text/javascript">
DtTvB_CHAT_GATEWAY = '<?php echo $ext_info['url']; ?>/index.php?mode=gateway';
DtTvB_CHAT_CSRF = '<?php echo generate_form_token($ext_info['url'] . '/index.php?mode=gateway'); ?>';
</script>
<script type="text/javascript" src="<?php echo $ext_info['url']; ?>/chat.js"></script>


<?php

// Display footer
($hook = get_hook('xn_dtchat_end')) ? (defined('FORUM_USE_INCLUDE') ? include $hook : eval($hook)) : null;
$tpl_temp = forum_trim(ob_get_contents());
$tpl_main = str_replace('<!-- forum_main -->', $tpl_temp, $tpl_main);
ob_end_clean();
require FORUM_ROOT.'footer.php';
